<template>
  <div>
    <el-card>
      <h2>申请奖学金</h2>
      
      <!-- 奖学金列表 -->
      <el-card style="margin-bottom: 20px;">
        <h3>可申请的奖学金</h3>
        <el-table :data="scholarships" @row-click="selectScholarship" style="cursor: pointer;">
          <el-table-column prop="name" label="奖学金名称"/>
          <el-table-column prop="maxAmount" label="金额">
            <template #default="scope">
              {{ scope.row.maxAmount }}元
            </template>
          </el-table-column>
          <el-table-column prop="level" label="级别"/>
          <el-table-column prop="year" label="评定年度"/>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button 
                type="primary" 
                size="small" 
                @click.stop="selectScholarship(scope.row)"
              >
                申请
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 申请表单 -->
      <el-card v-if="selectedScholarship">
        <h3>申请表单</h3>
        <el-form :model="form" @submit.prevent="submitApplication" label-width="120px">
          <el-form-item label="奖学金名称">
            <el-input v-model="selectedScholarship.name" disabled/>
          </el-form-item>
          <el-form-item label="申请理由" required>
            <el-input 
              v-model="form.reason" 
              type="textarea" 
              :rows="4"
              placeholder="请详细说明申请理由，包括个人成绩、科研成果、社会服务等方面..."
            />
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input 
              v-model="form.contact" 
              placeholder="请输入11位手机号或邮箱地址"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" native-type="submit" :loading="submitting">
              提交申请
            </el-button>
            <el-button @click="cancelApplication">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 我的申请记录 -->
      <el-card style="margin-top: 20px;">
        <h3>我的申请记录</h3>
        <el-table :data="myApplications">
          <el-table-column prop="scholarshipName" label="奖学金名称"/>
          <el-table-column prop="applyDate" label="申请日期"/>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag v-if="scope.row.status === '申请中' || scope.row.status === 'pending'" type="info">申请中</el-tag>
              <el-tag v-else-if="scope.row.status === '已通过' || scope.row.status === 'approved'" type="success">已通过</el-tag>
              <el-tag v-else-if="scope.row.status === '已拒绝' || scope.row.status === 'rejected'" type="danger">已拒绝</el-tag>
              <el-tag v-else type="info">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="审核意见"/>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const scholarships = ref([])
const selectedScholarship = ref(null)
const myApplications = ref([])
const submitting = ref(false)

const form = ref({
  reason: '',
  contact: ''
})

const studentId = localStorage.getItem('studentId')

// 验证联系方式格式
const validateContact = (contact) => {
  if (!contact || contact.trim() === '') {
    return { valid: false, message: '请填写联系方式' }
  }
  
  const trimmedContact = contact.trim()
  
  // 验证手机号格式（11位数字）
  const phoneRegex = /^1[3-9]\d{9}$/
  if (phoneRegex.test(trimmedContact)) {
    return { valid: true, message: '' }
  }
  
  // 验证邮箱格式
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (emailRegex.test(trimmedContact)) {
    return { valid: true, message: '' }
  }
  
  return { valid: false, message: '联系方式格式不正确，请输入11位手机号或有效的邮箱地址' }
}

// 获取可申请的奖学金列表
const fetchScholarships = async () => {
  try {
    const res = await axios.get('/scholarships')
    scholarships.value = res.data
  } catch (e) {
    ElMessage.error('获取奖学金列表失败')
    scholarships.value = []
  }
}

// 提交申请
const submitApplication = async () => {
  console.log('开始提交申请...')
  console.log('当前学生ID:', studentId)
  console.log('selectedScholarship.value:', selectedScholarship.value)
  console.log('selectedScholarship.value?.scholarshipId:', selectedScholarship.value?.scholarshipId)
  
  if (!studentId) {
    ElMessage.error('学生ID不存在，请重新登录')
    return
  }
  
  if (!form.value.reason.trim()) {
    ElMessage.warning('请填写申请理由')
    return
  }

  // 验证联系方式格式
  const contactValidation = validateContact(form.value.contact)
  if (!contactValidation.valid) {
    ElMessage.warning(contactValidation.message)
    return
  }

  if (!selectedScholarship.value || !selectedScholarship.value.scholarshipId) {
    console.log('奖学金选择验证失败:')
    console.log('- selectedScholarship.value 存在:', !!selectedScholarship.value)
    console.log('- scholarshipId 存在:', !!selectedScholarship.value?.scholarshipId)
    ElMessage.error('请先选择要申请的奖学金')
    return
  }

  try {
    submitting.value = true
    
    // 添加调试信息
    console.log('提交的申请数据:', {
      studentId: studentId,
      scholarshipId: selectedScholarship.value.scholarshipId,
      reason: form.value.reason,
      contact: form.value.contact.trim() // 去除首尾空格
    })
    
    // 检查是否已经申请过该奖学金
    const existingApplications = myApplications.value.filter(app => 
      app.scholarshipName === selectedScholarship.value.name
    )
    
    let confirmMessage = '确定要提交申请吗？'
    if (existingApplications.length > 0) {
      confirmMessage = `您已经申请过${selectedScholarship.value.name}，再次提交将覆盖之前的申请。确定要继续吗？`
    }
    
    // 显示确认对话框
    await ElMessageBox.confirm(confirmMessage, '确认申请', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 使用新的创建或更新接口
    const response = await axios.post('/scholarship-applications/create-or-update', {
      studentId: studentId,
      scholarshipId: selectedScholarship.value.scholarshipId,
      reason: form.value.reason,
      contact: form.value.contact.trim() // 去除首尾空格
    })
    
    if (response.status === 200) {
      if (existingApplications.length > 0) {
        ElMessage.success('申请已更新！')
      } else {
        ElMessage.success('申请提交成功！')
      }
      cancelApplication()
      // 延迟刷新申请记录，确保后端数据已更新
      setTimeout(() => {
        fetchMyApplications()
      }, 500)
    } else {
      ElMessage.error('申请提交失败，请重试')
    }
  } catch (e) {
    console.error('申请提交失败', e)
    if (e.response && e.response.data) {
      ElMessage.error(`申请提交失败: ${e.response.data}`)
    } else if (e.message && e.message.includes('取消')) {
      // 用户取消操作，不显示错误信息
      return
    } else {
      ElMessage.error('申请提交失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

// 获取我的申请记录
const fetchMyApplications = async () => {
  if (!studentId) return
  try {
    const res = await axios.get(`/scholarship-applications/search/student?studentId=${studentId}`)
    myApplications.value = res.data.map(app => {
      const scholarship = scholarships.value.find(s => s.scholarshipId === app.scholarshipId)
      return {
        scholarshipName: scholarship ? scholarship.name : '未知奖学金',
        applyDate: new Date(app.applyDate).toLocaleDateString(),
        status: app.status,
        remark: app.remark || ''
      }
    })
  } catch (e) {
    ElMessage.error('获取申请记录失败')
    myApplications.value = []
  }
}

// 选择奖学金
const selectScholarship = (scholarship) => {
  console.log('选择的奖学金:', JSON.stringify(scholarship, null, 2))
  selectedScholarship.value = scholarship
  console.log('selectedScholarship.value:', JSON.stringify(selectedScholarship.value, null, 2))
  form.value = {
    reason: '',
    contact: ''
  }
}

// 取消申请
const cancelApplication = () => {
  selectedScholarship.value = null
  form.value = {
    reason: '',
    contact: ''
  }
}

// 状态显示函数
const getStatusType = (status) => {
  switch (status) {
    case '申请中':
      return 'info'
    case '已通过':
      return 'success'
    case '已拒绝':
      return 'danger'
    default:
      return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case '申请中':
      return '审核中'
    case '已通过':
      return '已通过'
    case '已拒绝':
      return '已拒绝'
    default:
      return status
  }
}

onMounted(async () => {
  await fetchScholarships()
  await fetchMyApplications()
})
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}

h2, h3 {
  margin-bottom: 16px;
  color: #303133;
}

.el-table {
  margin-bottom: 16px;
}

.el-form {
  max-width: 600px;
}
</style>